/*! @azure/msal-browser v2.38.3 2023-10-27 */
'use strict';
import { __extends, __awaiter, __generator, __assign } from '../_virtual/_tslib.js';
import { AuthError, PerformanceEvents, Constants, StringUtils, PromptValue, UrlString, ProtocolUtils } from '@azure/msal-common';
import { StandardInteractionClient } from './StandardInteractionClient.js';
import { BrowserAuthError } from '../error/BrowserAuthError.js';
import { InteractionType } from '../utils/BrowserConstants.js';
import { SilentHandler } from '../interaction_handler/SilentHandler.js';
import { NativeMessageHandler } from '../broker/nativeBroker/NativeMessageHandler.js';
import { NativeInteractionClient } from './NativeInteractionClient.js';

/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
var SilentIframeClient = /** @class */ (function (_super) {
    __extends(SilentIframeClient, _super);
    function SilentIframeClient(config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, apiId, performanceClient, nativeStorageImpl, nativeMessageHandler, correlationId) {
        var _this = _super.call(this, config, storageImpl, browserCrypto, logger, eventHandler, navigationClient, performanceClient, nativeMessageHandler, correlationId) || this;
        _this.apiId = apiId;
        _this.nativeStorage = nativeStorageImpl;
        return _this;
    }
    /**
     * Acquires a token silently by opening a hidden iframe to the /authorize endpoint with prompt=none or prompt=no_session
     * @param request
     */
    SilentIframeClient.prototype.acquireToken = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            var acquireTokenMeasurement, silentRequest, serverTelemetryManager, authClient, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.performanceClient.addQueueMeasurement(PerformanceEvents.SilentIframeClientAcquireToken, request.correlationId);
                        this.logger.verbose("acquireTokenByIframe called");
                        acquireTokenMeasurement = this.performanceClient.startMeasurement(PerformanceEvents.SilentIframeClientAcquireToken, request.correlationId);
                        // Check that we have some SSO data
                        if (StringUtils.isEmpty(request.loginHint) && StringUtils.isEmpty(request.sid) && (!request.account || StringUtils.isEmpty(request.account.username))) {
                            this.logger.warning("No user hint provided. The authorization server may need more information to complete this request.");
                        }
                        // Check that prompt is set to none or no_session, throw error if it is set to anything else.
                        if (request.prompt && (request.prompt !== PromptValue.NONE) && (request.prompt !== PromptValue.NO_SESSION)) {
                            acquireTokenMeasurement.endMeasurement({
                                success: false
                            });
                            throw BrowserAuthError.createSilentPromptValueError(request.prompt);
                        }
                        // Create silent request
                        this.performanceClient.setPreQueueTime(PerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest, request.correlationId);
                        return [4 /*yield*/, this.initializeAuthorizationRequest(__assign(__assign({}, request), { prompt: request.prompt || PromptValue.NONE }), InteractionType.Silent)];
                    case 1:
                        silentRequest = _a.sent();
                        this.browserStorage.updateCacheEntries(silentRequest.state, silentRequest.nonce, silentRequest.authority, silentRequest.loginHint || Constants.EMPTY_STRING, silentRequest.account || null);
                        serverTelemetryManager = this.initializeServerTelemetryManager(this.apiId);
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 5, , 6]);
                        // Initialize the client
                        this.performanceClient.setPreQueueTime(PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, request.correlationId);
                        return [4 /*yield*/, this.createAuthCodeClient(serverTelemetryManager, silentRequest.authority, silentRequest.azureCloudOptions)];
                    case 3:
                        authClient = _a.sent();
                        this.logger.verbose("Auth code client created");
                        this.performanceClient.setPreQueueTime(PerformanceEvents.SilentIframeClientTokenHelper, request.correlationId);
                        return [4 /*yield*/, this.silentTokenHelper(authClient, silentRequest).then(function (result) {
                                acquireTokenMeasurement.endMeasurement({
                                    success: true,
                                    fromCache: false,
                                    requestId: result.requestId
                                });
                                return result;
                            })];
                    case 4: return [2 /*return*/, _a.sent()];
                    case 5:
                        e_1 = _a.sent();
                        if (e_1 instanceof AuthError) {
                            e_1.setCorrelationId(this.correlationId);
                        }
                        serverTelemetryManager.cacheFailedRequest(e_1);
                        this.browserStorage.cleanRequestByState(silentRequest.state);
                        acquireTokenMeasurement.endMeasurement({
                            errorCode: e_1 instanceof AuthError && e_1.errorCode || undefined,
                            subErrorCode: e_1 instanceof AuthError && e_1.subError || undefined,
                            success: false
                        });
                        throw e_1;
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * Currently Unsupported
     */
    SilentIframeClient.prototype.logout = function () {
        // Synchronous so we must reject
        return Promise.reject(BrowserAuthError.createSilentLogoutUnsupportedError());
    };
    /**
     * Helper which acquires an authorization code silently using a hidden iframe from given url
     * using the scopes requested as part of the id, and exchanges the code for a set of OAuth tokens.
     * @param navigateUrl
     * @param userRequestScopes
     */
    SilentIframeClient.prototype.silentTokenHelper = function (authClient, silentRequest) {
        return __awaiter(this, void 0, void 0, function () {
            var authCodeRequest, navigateUrl, silentHandler, msalFrame, hash, serverParams, state, nativeInteractionClient, userRequestState;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.performanceClient.addQueueMeasurement(PerformanceEvents.SilentIframeClientTokenHelper, silentRequest.correlationId);
                        // Create auth code request and generate PKCE params
                        this.performanceClient.setPreQueueTime(PerformanceEvents.StandardInteractionClientInitializeAuthorizationCodeRequest, silentRequest.correlationId);
                        return [4 /*yield*/, this.initializeAuthorizationCodeRequest(silentRequest)];
                    case 1:
                        authCodeRequest = _a.sent();
                        // Create authorize request url
                        this.performanceClient.setPreQueueTime(PerformanceEvents.GetAuthCodeUrl, silentRequest.correlationId);
                        return [4 /*yield*/, authClient.getAuthCodeUrl(__assign(__assign({}, silentRequest), { nativeBroker: NativeMessageHandler.isNativeAvailable(this.config, this.logger, this.nativeMessageHandler, silentRequest.authenticationScheme) }))];
                    case 2:
                        navigateUrl = _a.sent();
                        silentHandler = new SilentHandler(authClient, this.browserStorage, authCodeRequest, this.logger, this.config.system, this.performanceClient);
                        // Get the frame handle for the silent request
                        this.performanceClient.setPreQueueTime(PerformanceEvents.SilentHandlerInitiateAuthRequest, silentRequest.correlationId);
                        return [4 /*yield*/, silentHandler.initiateAuthRequest(navigateUrl)];
                    case 3:
                        msalFrame = _a.sent();
                        // Monitor the window for the hash. Return the string value and close the popup when the hash is received. Default timeout is 60 seconds.
                        this.performanceClient.setPreQueueTime(PerformanceEvents.SilentHandlerMonitorIframeForHash, silentRequest.correlationId);
                        return [4 /*yield*/, silentHandler.monitorIframeForHash(msalFrame, this.config.system.iframeHashTimeout)];
                    case 4:
                        hash = _a.sent();
                        serverParams = UrlString.getDeserializedHash(hash);
                        state = this.validateAndExtractStateFromHash(serverParams, InteractionType.Silent, authCodeRequest.correlationId);
                        if (serverParams.accountId) {
                            this.logger.verbose("Account id found in hash, calling WAM for token");
                            if (!this.nativeMessageHandler) {
                                throw BrowserAuthError.createNativeConnectionNotEstablishedError();
                            }
                            nativeInteractionClient = new NativeInteractionClient(this.config, this.browserStorage, this.browserCrypto, this.logger, this.eventHandler, this.navigationClient, this.apiId, this.performanceClient, this.nativeMessageHandler, serverParams.accountId, this.browserStorage, this.correlationId);
                            userRequestState = ProtocolUtils.parseRequestState(this.browserCrypto, state).userRequestState;
                            return [2 /*return*/, nativeInteractionClient.acquireToken(__assign(__assign({}, silentRequest), { state: userRequestState, prompt: silentRequest.prompt || PromptValue.NONE })).finally(function () {
                                    _this.browserStorage.cleanRequestByState(state);
                                })];
                        }
                        // Handle response from hash string
                        this.performanceClient.setPreQueueTime(PerformanceEvents.HandleCodeResponseFromHash, silentRequest.correlationId);
                        return [2 /*return*/, silentHandler.handleCodeResponseFromHash(hash, state, authClient.authority, this.networkClient)];
                }
            });
        });
    };
    return SilentIframeClient;
}(StandardInteractionClient));

export { SilentIframeClient };
//# sourceMappingURL=SilentIframeClient.js.map
